package myhistory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;

import javax.naming.NamingException;

import onlineAccessManagement.DBLib;

public class HistoryDao {
	
	Connection conn;
	String sql;
	PreparedStatement ps;
	
	int pageNo;	//第几页数
	int pageSize;	//一页显示多少数据
	int pageCount;	//总页数
	public int getPageNo() {
		return pageNo;
	}

	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getPageCount() {
		return pageCount;
	}

	public HistoryDao() throws NamingException, SQLException {
		conn=DBLib.getconn();
		sql="use Visitor";
		ps=conn.prepareStatement(sql);
		ps.executeUpdate();		
	}
	
	//将历史访问记录存入数据库的history表中
	public void saveHistory(History his) throws SQLException {
		sql="INSERT INTO history (visitId, visittime, url) VALUES (?, ?, ?)";
		ps=conn.prepareStatement(sql);		
		ps.setInt(1, his.getVisitId());
		ps.setTimestamp(2,new Timestamp(his.getVisittime().getTime()));
		ps.setString(3, his.getUrl());		
		ps.executeUpdate();
		conn.close();
	}
	//得到所有的访客信息
	public ArrayList<History> getHistory() throws SQLException{
		ArrayList<History> history=new ArrayList<History>();		
		sql="SELECT * FROM history";
		ps=conn.prepareStatement(sql);
		ResultSet rs=ps.executeQuery();
		while(rs.next()) {
			History his=new History();
			his.setId(rs.getInt(1));
			his.setVisitId(rs.getInt(2));
			his.setVisittime(rs.getTimestamp(3));
			his.setUrl(rs.getString(4));
			history.add(his);
		}
		conn.close();
		return history;
	}
	
	//得到当前页的数据
	public ArrayList<History> getPageData() throws SQLException, NamingException{
		if(conn.isClosed()) {
			conn=DBLib.getconn();
		}
		sql="select * from history limit " + (pageNo-1)*pageSize + "," + pageSize;
		ps=conn.prepareStatement(sql);
		ResultSet rs=ps.executeQuery();
		ArrayList<History> history=new ArrayList<History>();		
		while(rs.next()) {
			History his=new History();
			his.setId(rs.getInt(1));
			his.setVisitId(rs.getInt(2));
			his.setVisittime(rs.getTimestamp(3));
			his.setUrl(rs.getString(4));
			history.add(his);
		}
		conn.close();
		return history;
		
	}
	
	//计算总页数
	public void computePageCount() throws NamingException, SQLException {
		if(conn.isClosed()) {
			conn=DBLib.getconn();
		}
		sql="select count(*) from history";	//计算history中一共有多少条记录
		ps=conn.prepareStatement(sql);
		ResultSet rs=ps.executeQuery();
		rs.next();
		pageCount=rs.getInt(1);
		if(pageCount%pageSize==0) {
			pageCount=pageCount/pageSize;
		}else {
			pageCount=pageCount/pageSize +1;
		}
		conn.close();
	}
}
